//
//  ZCAllViewController.m
//  BaiSi
//
//  Created by 张灿 on 16/5/1.
//  Copyright © 2016年 张灿. All rights reserved.
//

#import "ZCAllViewController.h"
#import "ZCAllViewCell.h"
#import "ZCThemeItem.h"
#import <AFNetworking.h>
#import <MJExtension/MJExtension.h>
#import "ZCThemeViewModel.h"
#import <MJRefresh/MJRefresh.h>
#import "ZCEssenceViewController.h"


static NSString *ID = @"cell";
@interface ZCAllViewController ()

//模型数组
@property (nonatomic, strong) NSMutableArray *themeViewModels;

/** 请求管理者 */
@property (nonatomic, weak) AFHTTPSessionManager *manager;

//记录请求时间
@property (nonatomic, strong) NSNumber *maxtime;

//记录通知,用来销毁用的
@property (nonatomic, weak) id observe;


@end

@implementation ZCAllViewController

- (NSString *)list
{
    return [self.parentViewController isKindOfClass:[ZCEssenceViewController class]] ? @"list" : @"newlist";
}

- (ZCThemeType)type
{
    return ZCThemeTypeAll;
}

- (void)loadView
{
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds];
}

- (AFHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (NSArray *)themeViewModels
{
    if (_themeViewModels == nil) {
        _themeViewModels = [NSMutableArray array];
    }
    return _themeViewModels;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //注册cell
    [self.tableView registerClass:[ZCAllViewCell class] forCellReuseIdentifier:ID];
    
    //设置分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = RGB(217, 217, 217);
    
    //内偏移
    self.tableView.contentInset = UIEdgeInsetsMake(64 + 44 + 10, 0, 49, 0);
    
    
    //下拉刷新
    [self setupHeaderRefresh];
    
    //上拉刷新
    [self setupFooterRefresh];
    
    //加载网络数据
    [self.tableView.mj_header beginRefreshing];
    
    //监听tabBar重复点击
    _observe = [[NSNotificationCenter defaultCenter] addObserverForName:ZCRepeatClickTabTitleNote object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        if (self.tableView.window) {
            // 监听到通知就会调用
            // 判断下当前哪个控制器的view显示出来
            // 如果显示出来的view，都能拿到当前窗口
            [self.tableView.mj_header beginRefreshing];
        }
    }];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:_observe];
}

#pragma mark - 设置下拉刷新和下拉刷新
- (void)setupHeaderRefresh
{
    //创建下拉刷新控件
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    //自动透明
    header.automaticallyChangeAlpha = YES;
    
    self.tableView.mj_header = header;
}

- (void)setupFooterRefresh
{
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadmoreData)];
    footer.automaticallyHidden = YES;
    self.tableView.mj_footer = footer;
}


#pragma mark - 加载数据
- (void)loadData
{
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];

    //配置请求参数
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"a"] = self.list;
    dict[@"c"] = @"data";
    dict[@"type"] = @(self.type);
    
    //发送请求
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //结束下拉刷新
        [self.tableView.mj_header endRefreshing];
        
        _maxtime = responseObject[@"info"][@"maxtime"];
        NSArray *items = [NSArray array];
        NSMutableArray *arrs = [NSMutableArray array];

        //模型转数组
        items = [ZCThemeItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];

        for (ZCThemeItem *item in items) {
            ZCThemeViewModel *vm = [[ZCThemeViewModel alloc] init];
            vm.item = item;
            [arrs addObject:vm];
        }
        self.themeViewModels = arrs;
        
        
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //结束下拉刷新
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)loadmoreData
{
    //取消之前的请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    //配置请求参数
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"a"] = @"list";
    dict[@"c"] = @"data";
    dict[@"type"] = @(self.type);
    dict[@"maxtime"] = _maxtime;
    
    //发送请求
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //结束下拉刷新
        [self.tableView.mj_footer endRefreshing];
        
        NSArray *items = [NSArray array];
        NSMutableArray *arrs = [NSMutableArray array];
        
        //模型转数组
        items = [ZCThemeItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        for (ZCThemeItem *item in items) {
            ZCThemeViewModel *vm = [[ZCThemeViewModel alloc] init];
            vm.item = item;
            [arrs addObject:vm];
        }
        [_themeViewModels addObjectsFromArray:arrs];
        
        
        [self.tableView reloadData];
        _maxtime = responseObject[@"info"][@"maxtime"];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //结束下拉刷新
        [self.tableView.mj_footer endRefreshing];
    }];

}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.themeViewModels.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZCAllViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    ZCThemeViewModel *vm = self.themeViewModels[indexPath.row];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.vm = vm;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZCThemeViewModel *vm = self.themeViewModels[indexPath.row];
    return vm.cellH;
}

@end
